<?php
	
	require_once('../jacked_configMySQL.php');
    require('jacked_configsati.php');
	require('jacked_openidfunctions.php');
	
	//if this isn't getting called via API, we need this
	if(!function_exists('generateSourceID')){
		function generateSourceID(){
			//welp this is kind of a huge faggotry
			include_once('jacked_configapilol.php');
			$uuid = $_SERVER['REMOTE_ADDR'];
			$sourcedb = jackedDBGetRow(JACKED_APILOL_DB_SOURCES, "`uuid` = '$uuid'", JACKED_DEFAULT_LINK, MYSQL_ASSOC);
			if($sourcedb){
				//already have a source
				$source = array("id" => $sourcedb['id'], "uuid" => $sourcedb['uuid']);
			}else{
				//need to create a new source for this guy
				$source = array("id" => '', "uuid" => $uuid, "Application" => '52'); //this is the site goddammit
				$newID = jackedDBInsertValues(JACKED_APILOL_DB_SOURCES, $source);
				if(!$newID){
					return false;
				}
			}
			
			return $newID;
		}
	}
	
	//////////////////////////
	//         openid auth       //
	     //////////////////////////
	
	function getLoginWithOID($provider){
		return jackedOIDGetAuthRedirect($provider, array('contact/email'), array('namePerson/friendly'));
	}
	
	//not clean, uses $_GET directly
	function completeLoginWithOID(){
		return jackedOIDHandleAuthResponse();
	}
		

	//////////////////////////
	//            CAWMMENTS      //
	     //////////////////////////
		 
	function getCommentsCountForPost($postID){
		$query = "SELECT `id` FROM " . JACKED_SATI_DB_COMMENTS . " WHERE `postID` = '$postID' AND `approved` = '1'";
		
        $posts = jackedDBQuery($query, JACKED_DEFAULT_LINK);
		$done = 0;
		$num = mysql_num_rows($posts);
		
		if($num){
			$done = $num;
		}

        return $done;
	}
		 
	function getCommentsForPost($postID, $approved = true, $howMany = 0, $page = 1, $orderby = 'date_down', $fields = array("id", "score", "reply-to", "comment", "approved", "name", "date", "email", "openID", "Source")){
				
		$fieldstring = getFieldString($fields, array("id", "score", "reply-to", "comment", "approved", "name", "date", "email", "openID", "Source"));
		$query = "SELECT " . $fieldstring . " FROM " . JACKED_SATI_DB_COMMENTS . " WHERE `postID` = '$postID'";
		if($approved){
			$query .= " AND `approved` = '1'";
		}
		if($howMany != 0 && $page){
			$query .= paginator($howMany, $page);
		}
		$o = '';
		switch($orderby){
			case 'date_down':
				$o = " ORDER BY `date` DESC";
				break;
			
			case 'date_up':
				$o = " ORDER BY `date` ASC";
				break;
			
			case 'score_down':
				$o = " ORDER BY `score` DESC";
				break;
			
			case 'score_up':
				$o = " ORDER BY `score` ASC";
				break;
			
			default:
				$o = " ORDER BY `date` DESC";
				break;
		}
		
		$query .= $o;
		
        $posts = jackedDBQuery($query, JACKED_DEFAULT_LINK);
		$done = array();
		
		if($posts){
			while($row = mysql_fetch_array($posts, MYSQL_ASSOC)){
				$done[] = $row;
			}
		}

        return $done;
	}
		
	function getCommentThreadForPost($postID){
		$fieldstring = getFieldString($fields, array("id", "score", "reply-to", "comment", "approved", "name", "date", "email", "openID", "Source"));
		$query = "SELECT " . $fieldstring . " FROM " . JACKED_SATI_DB_COMMENTS . " WHERE `postID` = '$postID' AND `reply-to` = '0'";
        $posts = jackedDBQuery($query, JACKED_DEFAULT_LINK);
		$done = array();
		
		if($posts){
			while($row = mysql_fetch_array($posts, MYSQL_ASSOC)){
				$done[$row['id']] = $row;
				$done[$row['id']]['replies'] = getReplyThreadForComment($row['id']);
			}
		}

        return $done;
	}
	
	function getReplyThreadForComment($commentID){
		$comment = jackedDBGetResult(JACKED_SATI_DB_COMMENTS, "`reply-to` = '$commentID'", JACKED_DEFAULT_LINK, MYSQL_ASSOC);
		$thread = array();
		if($comment){
			while($row = mysql_fetch_array($comment, MYSQL_ASSOC)){
				$thread[$row['id']] = $row;
				$thread[$row['id']]['replies'] = getReplyThreadForComment($row['id']);
			}
		}
		return $thread;
	}
	
	function getCommentByID($id, $fields = array("id", "score", "reply-to", "comment", "approved", "name", "date", "email", "openID", "Source")){
				
		$fieldstring = getFieldString($fields, array("id", "score", "reply-to", "comment", "approved", "name", "date", "email", "openID", "Source"));
        $comment = jackedDBGetRowVals($fieldstring, JACKED_SATI_DB_COMMENTS, " `id` = '$id'", JACKED_DEFAULT_LINK, MYSQL_ASSOC);

        return $comment;
	}
	
	function postComment($postID, $comment, $replyID = 0){
	    $openid = API_getAuth('openid');
	    if($openid){
	        $newComment = array("id" => "",
								"postID" => $postID,
	                            "reply-to" => $replyID,
	                            "comment" => $comment,
	                            "approved" => 1,
	                            "name" => $openid['name'],
	                            "date" => time(),
	                            "email" => $openid['email'],
	                            "openID" => $openid['identity'],
								"score" => 0,
								"Source" => (function_exists('getMySourceID')? getMySourceID() : generateSourceID())
	                            );
	        return jackedDBInsertValues(JACKED_SATI_DB_COMMENTS, $newComment);
	    }else{
	        return false;
	    }
	}
	

	//////////////////////////
	//    VOETS FORE COMMANT     //
	     //////////////////////////
	
	function didSourceVoteOnComment($sourceID, $commentID){
		return (jackedDBgetRow(JACKED_SATI_DB_COMMENTSCORE, "`Comment` = '$commentID' AND `Source` = '$sourceID'", JACKED_DEFAULT_LINK, MYSQL_ASSOC))? true : false;
	}
	
	//returns the number of votes for a given comment,
	////if $updateCache is false, returns cached value
	////if its true, recalculates based on COMMENTSCORE table 
	////and updates cached value
	function getVotesForComment($commentID, $updateCache = false){
	    if($updateCache){
	        $query = "SELECT `value` FROM " . JACKED_SATI_DB_COMMENTSCORE . " WHERE `Comment` = '$commentID'";
	        $result = jackedDBQuery($query);
	        $votes = 0;
	        while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
	            $votes += $row['value'];
	        }
	        
	        jackedDBUpdate(JACKED_SATI_DB_COMMENTS, array("score" => $votes), "`id` = '$commentID'");
	    }else{
	        $votes = jackedDBGetVal('score', JACKED_SATI_DB_COMMENTS, "`id` = '$commentID'");
	    }
	    
	    return $votes;
	}
	
	function voteOnComment($commentID, $type, $sourceID){
	    $value = false;
	    if(!didSourceVoteOnComment($sourceID, $commentID)){
		
			//this is where to change to make certain sources have different score values
	        $value = ($type == 'sink')? -1 : 1;
			
	        $did = jackedDBInsertValues(JACKED_SATI_DB_COMMENTS, array("id" => '', "commentID" => $postID, "score" => $value, "Source" => $sourceID));
	        if($did){
	            $value = getVotesForComment($commentID, true);
	        }
	    }
	    return $value;
	} 
	
?>